<?php

namespace app\common\services;

use Exception;

use think\helper\Arr;
use GuzzleHttp\Client;
use think\facade\Cache;

/**
 * 企微
 */
class WeWork
{
    private static $config = array(
        'corpid'     => '',
        'corpsecret'    => '',
        'access_token' => '',
    );

    /**
     * [__construct 构造函数]
     * @param [type] $config [传递相关配置]
     */
    public function __construct($config = NULL)
    {
        $my_config = [
            'corpid' => env('wework.corpid'),
            'corpsecret' => env('wework.secret'),
        ];
        self::$config = array_merge(self::$config, $my_config);
        $config && self::$config = array_merge(self::$config, $config);
    }

    /**
     * [accessToken 获取 access_token]
     * @return [type] [description]
     */
    public static function accessToken(bool $refresh = false)
    {
        if ($refresh || !Cache::has('wework_access_token')) {
            $params = [
                'corpid' => self::$config['corpid'],
                'corpsecret' => self::$config['corpsecret'],
            ];

            $client = new Client();
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?' . http_build_query($params);
            $response = $client->request('GET', $url);
            $status = $response->getStatusCode();
            $body = $response->getBody()->getContents();
            if ($status != 200) {
                throw new Exception("error");
            }
            $result = json_decode($body, true) ?? [];
            if (!is_array($result)) {
                throw new Exception("error");
            }
            if (!empty($result['errcode'])) {
                throw new Exception($result['errmsg'] ?? 'error');
            }
            Cache::set('wework_access_token', $result['access_token'], $result['expires_in'] - 200);
        }

        return Cache::get('wework_access_token');
    }

    // 获取access_token
    public static function getAccessToken()
    {
        if (empty(self::$config['access_token'])) {
            $access_token = self::accessToken();
        } else {
            $access_token = self::$config['access_token'];
        }
        return $access_token;
    }

    /**
     * 获取登录信息
     * @param  string $code [code]
     */
    public static function getSession($code)
    {
        $access_token = self::getAccessToken();
        $params = [
            'access_token' => $access_token,
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];

        $client = new Client();
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?' . http_build_query($params);
        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();
        if ($status != 200) {
            throw new Exception("error");
        }
        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }


        return $result;
    }

    /**
     * 获取成员信息
     * @param  string $userId [userId]
     */
    public static function getUserInfo($userId)
    {
        $access_token = self::getAccessToken();
        $params = array(
            'access_token' => $access_token,
            'userid'    => $userId,
        );
        $client = new Client();
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?' . http_build_query($params);
        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();
        if ($status != 200) {
            throw new Exception("error");
        }
        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result;
    }

    /**
     * 联系我组件ID
     * @param  string $userId [userId]
     */
    public static function addContactWay($user_id)
    {
        $access_token = self::getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token=" . $access_token;

        $client = new Client();

        $params = [
            'type' => 1,
            'scene' => 1,
            'user' => [$user_id],
        ];
        $response = $client->request('POST', $url, ['json' => $params]);

        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['config_id'];
    }

    /**
     * 手机号换取成员ID
     * @param  string $mobile [mobile]
     */
    public static function getUserIdByPhone($mobile)
    {
        $access_token = self::getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" . $access_token;

        $client = new Client();

        $params = [
            'mobile' => $mobile,
        ];
        $response = $client->request('POST', $url, ['json' => $params]);

        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['userid'];
    }

    /**
     * 获取外部联系人信息
     * @param  string $userId [userId]
     */
    public static function getExternalcontactInfo($userId)
    {
        $access_token = self::getAccessToken();
        $params = array(
            'access_token' => $access_token,
            'external_userid'    => $userId,
        );
        $client = new Client();
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?' . http_build_query($params);
        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();
        if ($status != 200) {
            throw new Exception("error");
        }
        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['external_contact'];
    }

    /**
     * 发送消息
     */
    public static function sendMessage($params)
    {
        $access_token = self::getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . $access_token;
        $client = new Client();

        $response = $client->request('POST', $url, ['json' => $params]);

        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return true;
    }

    /**
     * 获取jsapi_ticket
     */
    public function getJsapiTicket()
    {
        if (Cache::has('wework_jsapi_ticket')) {
            return Cache::get('wework_jsapi_ticket');
        }
        $access_token = self::getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" . $access_token;
        $client = new Client();

        $response = $client->request('GET', $url);

        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        Cache::set('wework_jsapi_ticket', $result['ticket'], $result['expires_in'] - 200);
        return $result['ticket'];
    }

    /**
     * 获取应用ticket
     */
    public function getAgentTicket()
    {
        if (Cache::has('wework_agent_ticket')) {
            return Cache::get('wework_agent_ticket');
        }
        $access_token = self::getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=" . $access_token . '&type=agent_config';
        $client = new Client();

        $response = $client->request('GET', $url);

        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        Cache::set('wework_agent_ticket', $result['ticket'], $result['expires_in'] - 200);
        return $result['ticket'];
    }

    /**
     * 批量获取客户详情
     */
    public function getExternalList($params)
    {
        $access_token = self::getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=" . $access_token;
        $client = new Client();

        $response = $client->request('POST', $url, ['json' => $params]);

        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result;
    }

    /**
     * code换取用户ID
     */
    public function getUserByCode($code)
    {
        $params = [
            'access_token' => self::getAccessToken(),
            'code' => $code,
        ];

        $url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?" . http_build_query($params);
        $client = new Client();

        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['userid'];
    }

    /**
     * 生成静默授权链接
     */
    public function getCodeUrl($url){
        $params = [
            'appid'=>self::$config['corpid'],
            'redirect_uri' => urlencode($url),
            'response_type'=> 'code',
            'scope'=> 'snsapi_base',
            'agentid'=> env('wework.agent_id'),

        ];
        return sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?%s#wechat_redirect",http_build_query($params));
    }

    public function getCorpTagList(){
        $params = [
            'access_token' => self::getAccessToken(),
        ];

        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?" . http_build_query($params);
        $client = new Client();

        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['tag_group'];
    }

    public function MarkTag($params){
        $access_token = self::getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token=" . $access_token;

        $client = new Client();
        $response = $client->request('POST', $url, ['json' => $params]);

        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result;
    }

    public function getDeptList($id = ''){
        $params = [
            'access_token' => self::getAccessToken(),
            'id' => $id,
        ];

        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?" . http_build_query($params);
        $client = new Client();

        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['department_id'];
    }

    public function getDeptDetail($id)
    {
        $params = [
            'access_token' => self::getAccessToken(),
            'id' => $id,
        ];
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/get?" . http_build_query($params);
        $client = new Client();
        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['department'];
    }

    public function getDeptUserDetail($dept_id)
    {
        $params = [
            'access_token' => self::getAccessToken(),
            'department_id' => $dept_id,
        ];
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?" . http_build_query($params);
        $client = new Client();
        $response = $client->request('GET', $url);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        if ($status != 200) {
            throw new Exception("error");
        }

        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['errcode'])) {
            throw new Exception($result['errmsg'] ?? 'error');
        }
        return $result['userlist'];
    }
}
